import { Loader } from "./Loader"

export interface Paged<Data> {
    total: number,
    list: Data[]
}

export class PagedLoader<Data = any> extends Loader<Paged<Data>> {
    pageSize = 10
    private currentPage = 0
    private loadingPage = 0
    get hasMore(): boolean {
        if (this.data) {
            return this.data.list.length < this.data.total
        } else {
            return false
        }
    }
    get isReloading(): boolean {
        return this.isLoading && this.loadingPage === 1
    }
    get isLoadingMore(): boolean {
        return this.isLoading && this.loadingPage > 1
    }

    constructor(api: string | ((params: any, signal: AbortSignal) => Promise<Paged<Data>>), dynamicParams?: () => object) {
        super(api, dynamicParams)
    }

    override async load(params?: any): Promise<Paged<Data>> {
        this.loadingPage = 1
        const result = await super._load({ ...params, pageSize: this.pageSize })
        this.currentPage = this.loadingPage
        this._data = result
        return result
    }

    async loadMore(length?: number): Promise<Paged<Data>> {
        if (this.isLoading) {
            throw Error('请等待加载完成')
        }
        if (!this.data) { return this.load() }
        if (!this.hasMore) {
            throw Error('无更多数据')
        }
        this.loadingPage = this.currentPage + 1
        const data = this.data
        const result = await super.load({
            page: this.loadingPage,
            pageSize: length || this.pageSize
        })
        this.currentPage = this.loadingPage
        result.list.unshift(...data.list)
        this._data = result
        return result
    }
}
